﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace OrderManagement
{
    public class OrderService
    {
        private List<Order> orderList;

        public OrderService()
        {
            orderList = new List<Order>();
        }

        public List<Order> GetOrderList()
        {
            return orderList;
        }

        public void AddOrder(Order order)
        {
            if (orderList.Contains(order))
            {
                throw new Exception($"订单{order.OrderId}已经存在");
            }
            foreach (var detail in order.OrderDetails)
            {
                if (order.OrderDetails.Count(d => d.Equals(detail)) > 1)
                {
                    throw new Exception($"订单{order.OrderId}中商品{detail.Product.ProductName}的订单明细重复");
                }
            }
            orderList.Add(order);
        }

        public void RemoveOrder(Order order)
        {
            Order toRemove = orderList.Where(o => o.Equals(order)).FirstOrDefault();
            if (toRemove == null)
            {
                throw new Exception($"订单{order.OrderId}不存在，无法删除");
            }
            orderList.Remove(toRemove);
        }

        public void UpdateOrder(Order newOrder)
        {
            Order toUpdate = orderList.Where(o => o.Equals(newOrder)).FirstOrDefault();
            if (toUpdate == null)
            {
                throw new Exception($"订单{newOrder.OrderId}不存在，无法更新");
            }
            orderList.Remove(toUpdate);
            orderList.Add(newOrder);
        }

        public List<Order> QueryOrder(string keyword)
        {
            var query = from order in orderList
                        where order.OrderId.ToString().Contains(keyword) ||
                              order.Customer.CustomerName.Contains(keyword) ||
                              order.OrderDetails.Any(detail => detail.Product.ProductName.Contains(keyword))
                        orderby order.TotalAmount descending
                        select order;
            return query.ToList();
        }

        public List<Order> QueryOrder(double minAmount)
        {
            var query = from order in orderList
                        where order.TotalAmount > minAmount
                        orderby order.TotalAmount descending
                        select order;
            return query.ToList();
        }

        public void SortOrders()
        {
            orderList.Sort((o1, o2) => o1.OrderId - o2.OrderId);
        }

        public void SortOrders(Comparison<Order> comparison)
        {
            orderList.Sort(comparison);
        }

        public override string ToString()
        {
            string orderListString = "";
            foreach (Order order in orderList)
            {
                orderListString += order.ToString() + "\n\n";
            }
            return "订单列表：\n" + orderListString;
        }
    }
}